package com.kgc.dao;

import com.kgc.entity.Building;
import com.kgc.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BuildingDao extends BaseDao {

    public List<Building> selectPage(PageUtils pageUtils, String name) {
        List<Building> list = new ArrayList<>();
        try {
            String sql = "select * from building ";
            if (StringUtils.isNotEmpty(name)) { // 字符串是否为空
                sql += " where name like '%" + name + "%'";
            }
            sql += " limit ?,?";
            ResultSet rs = super.getExecuteQuery(sql, pageUtils.start(), pageUtils.getPageSize());
            while (rs.next()) {
                list.add(new Building(rs.getInt(1), rs.getString(2), rs.getInt(3)));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            super.closeConnection();
        }
        return list;
    }

    public int totalCount(String name) {
        try {
            String sql = "select count(*) from building ";
            if (StringUtils.isNotEmpty(name)) { // 字符串是否为空
                sql += " where name like '%" + name + "%'";
            }
            ResultSet rs = super.getExecuteQuery(sql);
            if (rs.next()) {
                return rs.getInt(1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            super.closeConnection();
        }
        return 0;
    }

    public int addBuilding(Building building) {
        String sql = "INSERT INTO `building`(`name`, `type`) VALUES (?, ?)";
        return super.getExecuteUpdate(sql, building.getName(), building.getType());
    }

    public int deleteBuilding(String id) {
        String sql = "delete from `building` where id = ?";
        return super.getExecuteUpdate(sql, id);
    }

    public int updateBuilding(Building building) {
        String sql = "UPDATE `building` SET `name` = ?, `type` = ? WHERE `id` = ?";
        return super.getExecuteUpdate(sql, building.getName(), building.getType(), building.getId());
    }
}
